package com.power.algorithm;

import java.util.Arrays;

/**
 * @description:
 * @author: jiangnan
 * @time: 2021/6/16 3:22 下午
 */
public class Solution26 {

    /**
     * 条件1 有序数组
     * 条件2 重复的元素
     * 条件3 空间O(1)
     * <p>
     * 快慢指针找中点反转
     * 快慢指针对比连续重复的元素
     */
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 1) {
            return nums.length;
        }
        int i = 0, j = 1;
        while (j < nums.length) {
            if (nums[i] == nums[j]) {
                j++;
            } else {
                i++;
                nums[i] = nums[j];
                j++;
            }
        }
        System.out.println(Arrays.toString(nums));
        return i + 1;
    }


    public int removeDuplicates2(int[] nums) {
        if (nums.length == 1 || nums == null) {
            return nums.length;
        }
        int left = 0, right = 1;
        while (right < nums.length) {
            if (nums[left] == nums[right]) {
                right++;
            } else {

                nums[++left] = nums[right];

            }
        }
        System.out.println(Arrays.toString(nums));
        return left + 1;
    }

    public static void main(String[] args) {
        int nums[] = {1, 2, 3, 3, 4, 6, 6, 7, 8};
        Solution26 solution26 = new Solution26();
        System.out.println(solution26.removeDuplicates(nums));
        System.out.println(solution26.removeDuplicates2(nums));
        System.out.println(solution26.removeDuplicates3(nums));
    }
    public int removeDuplicates3(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int p = 0;
        int q = 1;
        while(q < nums.length){
            if(nums[p] != nums[q]){
                nums[p + 1] = nums[q];
                p++;
            }
            q++;
        }
        return p + 1;
    }

}
